package cn.com.haopy.yue.ai.core.config.shiro;


import cn.com.haopy.yue.ai.core.utils.bcrypt.BCryptPasswordEncoder;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSAdmin;
import cn.com.haopy.yue.ai.db.service.hos.HOSAdminService;
import cn.com.haopy.yue.ai.db.service.hos.HOSPermissionService;
import cn.com.haopy.yue.ai.db.service.hos.HOSRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private HOSAdminService adminService;
    @Autowired
    private HOSRoleService roleService;
    @Autowired
    private HOSPermissionService permissionService;

    public AdminAuthorizingRealm() {
        //设置只处理OrgAdminUsernamePasswordToken类型
        setAuthenticationTokenClass(AdminUsernamePasswordToken.class);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        if (!(principals.getPrimaryPrincipal() instanceof HOSAdmin)) {
            return null;
        }

        HOSAdmin admin = (HOSAdmin) getAvailablePrincipal(principals);
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        System.out.println("token instanceof AdminUsernamePasswordToken:");
        System.out.println(token instanceof AdminUsernamePasswordToken);
        return token instanceof AdminUsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        if (token.getPrincipal() == null) {
            return null;
        }

        AdminUsernamePasswordToken upToken = (AdminUsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());

        if (!StringUtils.hasText(username)) {
            throw new AccountException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new AccountException("密码不能为空");
        }

        List<HOSAdmin> adminList = adminService.findByName(username);
        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if (adminList.isEmpty()) {
            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");
        }
        HOSAdmin admin = adminList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, admin.getPassword())) {
            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");
        }

        return new SimpleAuthenticationInfo(admin, password, getName());
    }

}
